
package com.android.base.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseBindingAdapter<M, B extends ViewDataBinding> extends RecyclerView.Adapter<BaseBindingAdapter<M, B>.BaseBindingViewHolder> {

    protected Context mContext;
    private int itemId;
    private int variableId;
    protected List<M> mList = new ArrayList<>();

    public BaseBindingAdapter(Context context) {
        this.mContext = context;
    }

    public BaseBindingAdapter(@LayoutRes int itemId, int variableId) {
        this.itemId = itemId;
        this.variableId = variableId;
        mList = new ArrayList<>();
    }

    public BaseBindingAdapter(List<M> data, @LayoutRes int itemId, int variableId) {
        this.mList = data == null ? new ArrayList<>() : data;
        this.itemId = itemId;
        this.variableId = variableId;
    }

//    public List<M> getList() {
//        return mList;
//    }
//
//    public void setList(List<M> list) {
//        this.mList = list;
//    }

    @Override
    public int getItemCount() {
        return null == this.mList ? 0 : this.mList.size();
    }

    @Override
    @NonNull
    public BaseBindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        B binding = DataBindingUtil.inflate(LayoutInflater.from(this.mContext), this.getLayoutResId(viewType), parent, false);
        return new BaseBindingViewHolder(binding.getRoot());
    }

    private void onBindViewHolder(M data, B binding, int position) {
    }

    @Override
    public void onBindViewHolder(BaseBindingViewHolder holder, final int position) {
        B binding = DataBindingUtil.getBinding(holder.itemView);
        this.onBindItem(binding, this.mList.get(position), holder);
        if (binding != null) {
            binding.executePendingBindings();
        }
    }

    public void setList(List<M> data) {
        this.mList.clear();
        this.mList.addAll(data);
        notifyDataSetChanged();
    }

    public List<M> getList() {
        return mList;
    }

    public void addData(M data) {
        this.mList.add(data);
        notifyDataSetChanged();
    }


    public void addData(List<M> data) {
        this.mList.addAll(data);
        notifyDataSetChanged();
    }


    protected abstract @LayoutRes
    int getLayoutResId(int viewType);
    protected abstract void onBindItem(B binding, M item, RecyclerView.ViewHolder holder);

    public class BaseBindingViewHolder extends RecyclerView.ViewHolder {
        BaseBindingViewHolder(View itemView) {
            super(itemView);
        }
    }
}